<template>
    <div class="blogshow">

        <div class="blogLook">
            <h1>{{item.title}}</h1>
            <h3>作者：{{item.loginname}}</h3>
            <h5>写作时间：{{timeConvert(item.createtime,2)}}</h5>
            <span v-html="htmlDecodeByRegExp(item.content)"></span>
        </div>
        <!-- newval. -->



        <div class="but">
            <el-button type="success" @click="back">返回</el-button>
            <el-button type="warning" v-if="item.loginId==user.loginId" @click="updateBlog">修改</el-button>
            <el-button type="danger" v-if="item.loginId==user.loginId" @click="delectItem">删除</el-button>
        </div>
        
        <!-- 下载pdf文件开始 -->
        <!-- <div class="el-icon-s-order myPdf" @click="prinkPdf">
        </div> -->

        <el-popover
            placement="top-start"
            width="50"
            trigger="hover"
            content="下载为PDF文件">
            <div class="el-icon-s-order myPdf" @click="getPdf(item)" slot="reference"></div>

        </el-popover>
        <!-- 下载pdf文件结束 -->
    </div>
</template>

<script>
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

export default {
    data () {
      return {
          id:"",
          itemUrl:this.pathUrl.itemUrl,//获取博客内容
          delectItemUrl:this.pathUrl.delectItemUrl,//删除博客路径
        //   itemUrl:"http://localhost:3003/api/blog/item",//获取博客内容
        //   delectItemUrl:"http://localhost:3003/api/blog/del",//删除博客路径
          item:"",//内容
          user:"",
      }
    },
    methods: {
        /**
         * 内容转码
         */
        htmlDecodeByRegExp (str){  
        var temp = "";
        if(str == "") return "";
            temp = str.replace(/&amp;/g,"&");
            temp = temp.replace(/&lt;/g,"<");
            temp = temp.replace(/&gt;/g,">");
            temp = temp.replace(/&nbsp;/g," ");
            temp = temp.replace(/&#39;/g,"\'");
            temp = temp.replace(/&quot;/g,"\"");
            // console.log(temp)
            return temp;  
        },
        /**
         * 成功提示
         */
        open2(message) {
            this.$message({
            showClose: true,
            message,
            type: 'success',
            duration:1500,
            });
        },
        /**
         * 取出汉字
         * 
         */
        GetChinese(strValue) {  
            if(strValue!= null && strValue!= ""){  
                var reg = /[\u4e00-\u9fa5]/g;   
                return strValue.match(reg).join("");  
            }  
            else  
                return "";  
        } ,
        /**
         * 获取路由iD
         */
        getId(){
            this.id=this.$route.query.id
        },
        /**
         * 获取单个博客内容
         */
        getItem(){
            this.$axios.post(this.itemUrl,{id:this.id})
            .then((result) => {
                // console.log(result.data[0])
                this.item=result.data[0]
            }).catch((err) => {
                console.log(err)
            });
        },
        /**
         * 获取用户
         */
        getUser(){
            this.user=JSON.parse(localStorage.getItem("user"))
        },
        /**
         * 时间戳格式化
         */
        timeConvert(timestamp,num){//num:0 YYYY-MM-DD  num:1  YYYY-MM-DD hh:mm:ss // timestamp:时间戳 
            timestamp = timestamp+'';
            timestamp = timestamp.length==10?timestamp*1000:timestamp;
            var date = new Date(timestamp);
            var y = date.getFullYear();  
            var m = date.getMonth() + 1;  
            m = m < 10 ? ('0' + m) : m;  
            var d = date.getDate();  
            d = d < 10 ? ('0' + d) : d;  
            var h = date.getHours();
            h = h < 10 ? ('0' + h) : h;
            var minute = date.getMinutes();
            var second = date.getSeconds();
            minute = minute < 10 ? ('0' + minute) : minute;  
            second = second < 10 ? ('0' + second) : second; 
            if(num==0){
                return y + '-' + m + '-' + d;  
            }else{
                return y + '-' + m + '-' + d +' '+ h +':'+ minute +':' + second;  
            }
        },
        /**
         * 放回上一页
         */
        back(){
            // window.history.go(-1)
            window.history.go(-1)
        },
        /**
         * 删除博客内容
         */
        delectItem(){
            this.$axios.post(this.delectItemUrl,{
                id:this.id,
                loginId:this.user.loginId
            })
            .then(r=>{
                if(r) this.open2("删除成功");
                this.$router.push("/blog/myblog")
            })
            .catch(err=>{
                console.log(err)
            })
        },
        /**
         * 修改博客内容
         */
        updateBlog(){
            this.item.content=this.htmlDecodeByRegExp(this.item.content)
            localStorage.setItem("item",JSON.stringify(this.item))
            this.$router.push("/blog/update")
        },
        /**
         * 下载PDF文件
         */
        getPdf(item){
             var target = document.querySelector(".blogLook");
            //  console.log(target)
            target.style.background = "#FFFFFF";

             html2Canvas(target, {
                // allowTaint: true
                // useCORS: true
            }).then(function (canvas) {
                let contentWidth = canvas.width//图片宽度
                let contentHeight = canvas.height//图片高度

                let pageHeight = contentWidth / 592.28 * 841.89//PDF的宽度
                let leftHeight = contentHeight//PDF的长度
                let position = 0
                let imgWidth = 595.28
                let imgHeight = 592.28 / contentWidth * contentHeight
                let pageData = canvas.toDataURL('image/jpeg', 1.0)
                // let pageData = canvas.toDataURL()
                let PDF = new JsPDF('', 'pt', 'a4')
                if (leftHeight < pageHeight) {
                PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
                } else {
                while (leftHeight > 0) {
                    PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                    leftHeight -= pageHeight
                    position -= 841.89
                    if (leftHeight > 0) {
                    PDF.addPage()
                    }
                }
                }
                PDF.save(item.title + '.pdf')
            }
            )

        }
    },
    mounted:function(){
        this.getId();
        this.getItem()
        this.getUser()
    },
    watch:{
        item: function(newval){
            this.item=newval
            console.log(this.item)
        }
    },
    components: {},
}
</script>

<style scoped>
.blogshow>*{
    width: 100%;
    /* text-align: center; */
}
.blogLook>h1,.blogLook>h3,.blogLook>h5{
    text-align: center;
    margin-bottom: 10px;
}
.blogshow{

    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
}
.blogshow>.but{
    margin-top: 50px;
    margin-bottom: 50px;
    text-align: center;
}
.blogLook{
    padding: 20px 10%;
}
.myPdf{
    position: fixed;
    top: 30%;
    left: 95%;
    height: 50px;
    width: 50px;
    font-size: 30px;
    color: #ffffff;
    text-align: center;
    line-height: 50px;
    background: #000000;
    border-radius: 10%;
    transform: translateX(-50%);
}
</style>